package com.dhcc.DRGsHosp.infra.util;

import java.util.Comparator;
import java.util.Map;

/**
 * 
 * @ClassName: MapSortByField  
 * @Description ：  listmap根据某个字段排序  
 * @Date: 2017年9月6日 下午8:14:54  
 * @Author LiuHongJun 
 * @Version 3.0.0 DHC-DRGs
 */
public class MapSortByField implements Comparator<Map<String, Object>> {
	private String key;
	private String sort;
	private String regular;
	/**
	 * 
	 * Creates a new instance of MapSortByField.  
	 *  @param key 排序的字段
	 *  @param sort 升序降序 desc  asc 
	 *  @param regular 替换的正则表达式
	 */
	public MapSortByField(String key, String sort,String regular){
		this.key = key;
		this.sort = sort;
		this.regular=regular;
	}
	@Override
	public int compare(Map<String, Object> m1, Map<String, Object> m2) {
		int returnValue = 1;
		if(null!=m1 && null!=m2){
			double d1 = 0;
			double d2 = 0;
			try{
				//根据正则表达式之外的字符
				d1 = m1.get(key)==null?0:Double.parseDouble(m1.get(key).toString().replaceAll(regular, ""));
				d2 = m2.get(key)==null?0:Double.parseDouble(m2.get(key).toString().replaceAll(regular, ""));
			}catch(Exception e){
				d1 = m1.get(key).hashCode();
				d2 = m2.get(key).hashCode();
			}
            if("desc".equals(sort)){
            	if(d1>d2){
                	returnValue = -1;
                }else if(d1==d2){
                	returnValue = 0;
                }else{
                	returnValue = 1;
                }
            } else if("asc".equals(sort)){
            	if(d1>d2){
                	returnValue = 1;
                }else if(d1==d2){
                	returnValue = 0;
                }else{
                	returnValue = -1;
                }
            }
        }
        return returnValue;
	}
}
